package com.ias.agdis_r.activity.more;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.adapter.WorkGroupListAdapter;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.workgroup.request.WorkGroupQueryUsersRequest;
import com.ias.agdis_r.terminalmanager.restful.workgroup.response.WorkGroupQueryUsersResponse;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.CUsers;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.Member;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.WorkGroupQueryUsersRequestVO;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.WorkGroupQueryUsersResponseVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.view.control.EditorTextClear;

import java.util.ArrayList;
import java.util.List;

import me.maxwin.view.XListView;

public class WorkGroupSearchActivity extends BaseActivity {

    EditorTextClear editText;
    XListView listView;
    WorkGroupListAdapter listAdapter;
    List<Member> members = new ArrayList<>();

    private int pageIndex = 1;      // 分页从第1页开始
    private int pageSize = 20;      // 每页大小
    private int pageCount = 1;      // 总页数
    private CharSequence queryText; // 查询关键字

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_group_search);
        initActionBar();
        initView();
    }

    private void initActionBar() {
        ActionBar actionBar = getActionBar();
        if (actionBar == null) {
            return;
        }
        actionBar.setCustomView(getLayoutInflater().inflate(R.layout.actionbar_settings, (ViewGroup) actionBar.getCustomView(), false));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        ((TextView) findViewById(R.id.txt_title)).setText(R.string.work_group_search);
        findViewById(R.id.actionbar_settings_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView() {
        editText = (EditorTextClear) findViewById(R.id.edit_text);
        listView = (XListView) findViewById(R.id.list_view);
        listView.setPullRefreshEnable(false);
        initListFooter();
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                // No Refresh
            }

            @Override
            public void onLoadMore() {
                // 分页加载
                queryMember();
            }
        });

        editText.addEditInputCompleteListener(new EditorTextClear.EditInputCompleteListener() {
            @Override
            public void inputCompleted(CharSequence charSequence) {
                initPage(charSequence);
                if (TextUtils.isEmpty(charSequence)) {
                    members.clear();
                    adapterNotifyDataSetChanged();
                    return;
                }
                // 模糊查询人员
                queryMember();
            }
        });

        listAdapter = new WorkGroupListAdapter(this, members);
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final Member item = (Member) parent.getItemAtPosition(position);
                if (item == null)
                    return;
                String message = getString(R.string.work_group_user_add, item.getMember_name());
                new AlertDialog.Builder(WorkGroupSearchActivity.this)
                        .setTitle(R.string.prompt)
                        .setMessage(message)
                        .setNegativeButton(R.string.canel, null)
                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                // 加入班组
                                Intent data = new Intent();
                                data.putExtra("member", item);
                                setResult(RESULT_OK, data);
                                finish();
                            }
                        }).show();
            }
        });
    }

    /** 初始化分页数据 */
    private void initPage(CharSequence charSequence) {
        pageIndex = 1;
        pageSize = 20;
        pageCount = 1;
        queryText = (charSequence != null ? charSequence : "");
    }

    /** 初始化ListView分页加载 */
    private void initListFooter() {
        if (members.isEmpty()) {                        // 空数据，无下一页
            listView.setPullLoadEnable(false);
        } else if (members.size() % pageSize != 0) {    // 最后一页数量没有填满（没有下一页）
            listView.setPullLoadEnable(false);
        } else if (pageIndex == pageCount){             // 最后一页数量填满，并且是最后一页（没有下一页）
            listView.setPullLoadEnable(false);
        } else {
            listView.setPullLoadEnable(true);           // 最后一页数量填慢，不是最后一页（下一页）
        }
    }

    /** 刷新列表适配器 */
    private void adapterNotifyDataSetChanged() {
        initListFooter();
        listAdapter.notifyDataSetChanged();
    }

    /** 查询人员(默认) */
    private void queryMember() {
        queryMember(queryText, pageIndex);
    }

    /**
     * 查询人员(分页)
     * @param text 关键字
     * @param pageIndex 页码
     */
    private void queryMember(CharSequence text, int pageIndex) {
        CUsers cUsers = new CUsers();
        if (S.isNumeric(text)) {
            cUsers.setUsno(text.toString());
        } else {
            cUsers.setName(text.toString());
        }

        WorkGroupQueryUsersRequestVO usersRequestVO = new WorkGroupQueryUsersRequestVO();
        usersRequestVO.setPageIndex(pageIndex);
        usersRequestVO.setPageSize(pageSize);
        usersRequestVO.setUser(cUsers);

        WorkGroupQueryUsersRequest queryUsersRequest = new WorkGroupQueryUsersRequest();
        queryUsersRequest.setWorkGroupQueryUserRequestVO(usersRequestVO);

        // 查询人员(分页)
        HttpUtil.getInstance().sendRequest(queryUsersRequest, MessageModel.WGQM, false);
    }

    /**
     * 人员查询响应处理
     * @param queryUsersResponse 响应结果
     */
    private void queryResponse(WorkGroupQueryUsersResponse queryUsersResponse) {
        WorkGroupQueryUsersResponseVO userResponseVO = queryUsersResponse.getWorkGroupQueryUserResponseVO();
        List<CUsers> cUsers = userResponseVO.getcUsers();
        pageIndex = userResponseVO.getPageIndex();

        if (pageIndex == 1) {   // 第一页为refresh，其他为add
            members.clear();
        }
        pageIndex++;
        if (cUsers == null || cUsers.isEmpty()) {
            adapterNotifyDataSetChanged();
            return;
        }

        Member member;
        for (CUsers users: cUsers) {
            String name = users.getName();
            String usno = users.getUsno();
            member = new Member();
            member.setMember_usno(usno);
            member.setMember_name(name);

            members.add(member);
        }
        adapterNotifyDataSetChanged();
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        switch (serviceId) {
            case MessageModel.WGQM:     // 查询人员
                queryResponse((WorkGroupQueryUsersResponse) response);
                break;
        }
    }

    @Override
    protected void updateUI(String tag) {

    }

}
